<?php 
	

	class AccountController extends BaseController{
	
		function singin() {
			// validate input
			$rules = array(
				'username' => 'required', 
				'password' => 'required' 
			);

			$validator = Validator::make(Input::all(), $rules);
			// if validate false return login page
			if ($validator->fails()) {
				return Redirect::to('login')
					->withErrors($validator) 
					->withInput(Input::except('password')); 
			} else {

				$userdata = array(
					'username' 	=> Input::get('username'),
					'password' 	=> Input::get('password')
				);

				if (Auth::attempt($userdata)) {
					$date = date_create();
					$date->getTimestamp();
					$user = Auth::user();
					$user->last_visited_time = $date;
					$user->save();
					return View::make('indexHome');

				} else {	 	
					$userdata = array(
						'email' 	=> Input::get('username'),
						'password' 	=> Input::get('password')
					);

					if (Auth::attempt($userdata)) {

						return View::make('indexHome');

					} else {
						return View::make('user.login',array('error1'=>'username or password not correct'));
					}
				}
			}
		}

		function signup(){
			$rules = array(
				'firstName' => 'required', 
				'lastName' 	=> 'required', 
				'username'	=> 'required',
				'email'  	=> 'required|email|unique:users', 
				'password' 	=> 'required',
				'sex' 		=> 'required' 
			);

			$validator = Validator::make(Input::all(), $rules);

			if ($validator->fails()) {
				return Redirect::to('signup')
					->withErrors($validator) 
					->withInput(Input::except('password')); 
			} else {
		        $confirmation_code = str_random(30);

				$ID = new ID();
		    	$ID->id_type_id = IDType::where('id_type_name','=','User')->first()->id;
		    	$ID->save();
		    	$ID = $ID->id;

		        $user = new User();
		        $user->nickname = Input::get('firstName') . Input::get('lastName');
		        $user->username = Input::get('username');
		        $user->email 	= Input::get('email');
		        $user->password = Hash::make(Input::get('password'));
		        $date = date_create();
				$date->getTimestamp();
				$user->last_visited_time = $date;
		        $user->confirmation_code = $confirmation_code;

		        $user = ID::find($ID)->user()->save($user);

		        $userInformation = new UserInformation();
		        $userInformation->firstname = Input::get('firstName');
		        $userInformation->lastname  = Input::get('lastName');
		        $userInformation->gender 	= Input::get('sex');
		        $userInformation = User::find($ID)->userInformation()->save($userInformation);

		        $data = array('key' => $confirmation_code, 'username' => Input::get('username'));
		        Mail::send('emails.verify', $data, function($message) {
		            $message->to(Input::get('email'), Input::get('username'))
		                ->subject('Verify your email address');
		        });

		        // */Flash::message('Thanks for signing up! Please check your email.');

		        Auth::loginUsingId($ID);
		    	return View::make('indexHome');
			}
		}

		function confirm($confirmation_code) {
			if( ! $confirmation_code)
	        {
	            // throw new InvalidConfirmationCodeException;
	            return Redirect::route('home');
	        }

	        $user = User::where('confirmation_code', '=', $confirmation_code)->first();

	        if ( ! $user)
	        {
	            // throw new InvalidConfirmationCodeException;
	            return Redirect::route('home');
	        }

	        $user->confirmed = 1;
	        $user->confirmation_code = null;
	        $user->save();

	        // Flash::message('You have successfully verified your account.');
	        if ( ! Auth::check())  Auth::login($user);
	        return Redirect::route('home');
		}
		
		function loginFb() {

			$code = Input::get('code');
		    if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
		   

		    $facebook = new Facebook(Config::get('facebook'));
		    $uid = $facebook->getUser();

		    if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');

		    $me = $facebook->api('/me');

		    $user = User::where('facebook_id', '=', $me['id'])->first();
		    $ID = 0;
		   /* $abc = array('la' => $_COOKIE['Latitude'], 'long' => $_COOKIE['Longitude'], 'add' => $_COOKIE['Address'] );*/
		    if (empty($user)) {
		    	$gender = 0; $city = 0;

		        if ($me['gender'] == 'male') $gender = 1;
		        else if ($me['gender'] == 'other') $gender = 3;
		        else $gender = 2;

		    	if ( isset($_COOKIE['Latitude']) ) {
		    		$address = explode(', ', $_COOKIE['Address']);
		    		
    				$city = City::where('city_name', '=', $address[2])->first()->id;
    				if ( empty($city) ) {
    					$country = Country::where('country_name', '=', $address[3])->first()->id;
    					if (empty($country)) {
    						$country = new Country();
							$country->country_name =  $address[3];
							$country->country_code = 'vn';
							$country->save();
							$country = $country->id;

							$city = new City();
							$city->city_name =  $address[2];
							$city = Country::find($country)->cities()->save($city);
							$city = $city->id;
    					} else {
    						$city = new City();
							$city->city_name =  $address[2];
							$city = Country::find($country)->cities()->save($city);
							$city = $city->id;
    					}
    				} 
    			}

		    	$ID = new ID();
		    	$ID->id_type_id = IDType::$types['User'];
		    	$ID->save();
		    	$ID = $ID->id;

		        $user = new User();
		        $user->nickname 	= $me['name'];
		        $user->facebook_id 	= $me['id'];
		        $user->email 		= $me['email'];
		        $user = ID::find($ID)->user()->save($user);
		        $date = date_create();
				$date->getTimestamp();
				$user->last_visited_time = $date;
		        $user = User::find($ID);

		      	$userInformation = new UserInformation();
		        $userInformation->firstname = $me['first_name'];
		        $userInformation->lastname  = $me['last_name'];
		        $userInformation->gender 	= $gender;
		        $userInformation->current_city_id = $city;
		        $userInformation = $user->userInformation()->save($userInformation);
		    } else {
		    	//loi cho nay 
		    	$date = date_create();
				$date->getTimestamp();
				$user->last_visited_time = $date;
				$user->save();
		    }
		    Auth::login($user);
		    return View::make('indexHome');
		}
	}